﻿using System;
using System.IO;
using System.Data;
using System.Web.Mail;
using System.Configuration;
using System.Data.SqlClient;

namespace EmailService
{
	/// <summary>
	/// EmailBS 的摘要说明。
	/// </summary>
	public class EmailBS
	{
		private const string DBConenctionKey = "DBConnStr";

		public EmailBS()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
		}

		public static void WriteEmailLog(string logstring)
		{
			DataSet ds = GetDataSet("EmailAccount", "");
			if(ds.Tables[0].Rows.Count == 0 || ds.Tables[0].Rows[0]["LogDir"].ToString() == "")
			{
				Exception e = new Exception("日志目录未定义！");
				throw e;
			}
			string dir = ds.Tables[0].Rows[0]["LogDir"].ToString();
			if(!System.IO.Directory.Exists(dir))
				System.IO.Directory.CreateDirectory(dir);

			string logfile = dir + 
				DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString() + ".txt";
			if(!File.Exists(logfile))
				using(FileStream fs = File.Create(logfile))
				{
				}

			StreamWriter sw = new StreamWriter(logfile, true);
			sw.WriteLine(logstring);
			sw.Close();
		}


		public static void SendEmail()
		{
			DataSet dsaccount = GetDataSet("EmailAccount", "");
			if(dsaccount.Tables[0].Rows.Count == 0 || dsaccount.Tables[0].Rows[0]["LogDir"].ToString() == "")
			{
				Exception e = new Exception("邮件发送参数未定义！");
				throw e;
			}

			DataRow row = dsaccount.Tables[0].Rows[0];
			if(row["State"].ToString() != "1")
				return;

			DataSet ds = GetDataSet("QueuedEmail", "NOT ISNULL(State,'0')='1'");
			foreach(DataRow dr in ds.Tables[0].Rows)
			{
				MailMessage mailmessage = new MailMessage();

				mailmessage.From = row["EmailAccount"].ToString();
				mailmessage.To = dr["To"].ToString();
				mailmessage.Subject = dr["Subject"].ToString();
				mailmessage.Body = dr["Body"].ToString();
                mailmessage.Headers.Add("Reply-To", dr["From"].ToString());
				mailmessage.BodyFormat = MailFormat.Html;

				mailmessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"] = mailmessage.From;	
　　			mailmessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = mailmessage.From;		
　　			mailmessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = row["AccountPassword"].ToString();
　　			mailmessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;			//验证级别0,1,2
　　			mailmessage.Fields["http://schemas.microsoft.com/cdo/configuration/languagecode"] = 0x0804;			//语言代码
　　			mailmessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = row["SmtpServer"].ToString();
　　            mailmessage.Fields["http://schemas.microsoft.com/cdo/configuration/languagecode"] = 0x0804; 
				mailmessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"]= "true";

				mailmessage.BodyFormat = MailFormat.Html;
				mailmessage.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");

				SmtpMail.SmtpServer = row["SmtpServer"].ToString();
				try
				{
　　				SmtpMail.Send(mailmessage);
					InsertSentEmail(Convert.ToInt32(dr["UserID"]), dr["From"].ToString(), dr["To"].ToString());

					UpdateQueuedEMailState(Convert.ToInt32(dr["QueuedEmailID"]), "1");

					//WriteEmailLog(DateTime.Now.ToString() + ":Sent Email OK From:" + dr["From"].ToString() + "  To:" + dr["To"].ToString() + "\nSubject:" + dr["Subject"].ToString());
				}
				catch(Exception ex)
				{
					//WriteEmailLog(DateTime.Now.ToString() + ":Sent Email From:" + dr["From"].ToString() + "  To:" + dr["To"].ToString() + "\nSubject:" + dr["Subject"].ToString());
					//WriteEmailLog(DateTime.Now.ToString() + ":Sent Email Error Message:" + ex.ToString());
				}
			}
		}


		public static DataSet GetDataSet(string tblname, string filter)
		{
			string sqlstr;
			if(filter != "")
				sqlstr = "SELECT * FROM " + tblname + " WHERE " + filter;
			else
				sqlstr = "SELECT * FROM " + tblname;
			SqlCommand cmd = new SqlCommand(sqlstr);
			cmd.CommandType = CommandType.Text;

			SqlConnection cn = new SqlConnection();
			cn.ConnectionString =  ConfigurationSettings.AppSettings[DBConenctionKey];
			cn.Open();

			cmd.Connection = cn;
			SqlDataAdapter da = new SqlDataAdapter(cmd);
			DataSet ds = new DataSet();
			da.Fill(ds);
			cn.Close();

			return ds;
		}

		public static void InsertSentEmail(int UserID, string FromEmailAddress, string ToEmailAddress)
		{
			SqlCommand cmd = new SqlCommand("sp_InsertSentEmail");
			cmd.CommandType = CommandType.StoredProcedure;

			SqlParameter paraUserID = cmd.CreateParameter();
			paraUserID.SqlDbType = SqlDbType.Int;
			paraUserID.ParameterName = "@UserID";
			paraUserID.Value = UserID;
			cmd.Parameters.Add(paraUserID);

			SqlParameter paraFrom = cmd.CreateParameter();
			paraFrom.SqlDbType = SqlDbType.NVarChar;
			paraFrom.ParameterName = "@FromEmailAddress";
			paraFrom.Value = FromEmailAddress;
			cmd.Parameters.Add(paraFrom);

			SqlParameter paraTo = cmd.CreateParameter();
			paraTo.SqlDbType = SqlDbType.NVarChar;
			paraTo.ParameterName = "@ToEmailAddress";
			paraTo.Value = ToEmailAddress;
			cmd.Parameters.Add(paraTo);

			SqlConnection cn = new SqlConnection();
			cn.ConnectionString =  ConfigurationSettings.AppSettings[DBConenctionKey];
			cn.Open();

			cmd.Connection = cn;
			
			cmd.ExecuteNonQuery();
			cn.Close();
		}


		public static bool UpdateQueuedEMailState(int QueuedEMailID, string State)
		{
			SqlCommand cmd = new SqlCommand("sp_UpdateQueuedEMailState");
			cmd.CommandType = CommandType.StoredProcedure;

			SqlParameter paraQueuedMailID = cmd.CreateParameter();
			paraQueuedMailID.SqlDbType = SqlDbType.Int;
			paraQueuedMailID.ParameterName = "@QueuedEMailID";
			paraQueuedMailID.Value = QueuedEMailID;
			cmd.Parameters.Add(paraQueuedMailID);

			SqlParameter paraState = cmd.CreateParameter();
			paraState.SqlDbType = SqlDbType.NVarChar;
			paraState.ParameterName = "@State";
			paraState.Value = State;
			cmd.Parameters.Add(paraState);

			SqlConnection cn = new SqlConnection();
			cn.ConnectionString =  ConfigurationSettings.AppSettings[DBConenctionKey];
			cn.Open();

			cmd.Connection = cn;
			cmd.ExecuteNonQuery();
			
			cn.Close();

			return true;
		}

	}
}
